package menu

import (
	"context"
	"go-zero-project/common/excption"
	"go-zero-project/services/user/rpc/constans"
	"go-zero-project/services/user/rpc/internal/mapper"
	"go-zero-project/services/user/rpc/internal/mapper/bo"

	"go-zero-project/services/user/rpc/internal/svc"
	"go-zero-project/services/user/rpc/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type DeleteMenuLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewDeleteMenuLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeleteMenuLogic {
	return &DeleteMenuLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *DeleteMenuLogic) DeleteMenu(in *pb.DeleteMenuReq) (*pb.EmptyObj, error) {
	// 1. check 下面是否存在子节点
	menuMapper := mapper.NewMenuMapper()
	selectCount, countErr := menuMapper.SelectCount(l.svcCtx.DBEngin, bo.SysMenuBO{ParentId: in.MenuId})
	if countErr != nil {
		return nil, countErr
	}
	if selectCount > 0 {
		return nil, excption.NewErrCode(constans.DeleteMenuError)
	}
	// 2.delete to db
	deleteErr := menuMapper.DeleteByMenuId(l.svcCtx.DBEngin, in.MenuId)
	if deleteErr != nil {
		return nil, deleteErr
	}
	return &pb.EmptyObj{}, nil
}
